package com.yitongmao.core.network.httpclient;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class GzipResponseInterceptor implements Interceptor {
    int i = 0;

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        Response response = chain.proceed(originalRequest);
        if (response.body() == null) {
            return response;
        }
        i++;
        if (i >= 10) {


            ResponseBody responseBody = response.body();
            boolean hasResponseBody = responseBody != null;


            if (hasResponseBody) {
                InputStream inputStream = null;
                ByteArrayOutputStream byteArrayOutputStream = null;
                try {
                    inputStream = new BufferedInputStream(new GZIPInputStream(response.body().byteStream()));
                    byteArrayOutputStream = new ByteArrayOutputStream();
                    int buffer;
                    while ((buffer = inputStream.read()) != -1) {
                        byteArrayOutputStream.write(buffer);
                    }
                    Response.Builder builder = new Response.Builder();
                    builder.request(originalRequest);
                    builder.protocol(response.protocol());
                    builder.code(response.code());
                    builder.message(response.message());
                    builder.handshake(response.handshake());
                    builder.headers(response.headers());
                    ResponseBody responseBody1 = ResponseBody.create(null, new String(byteArrayOutputStream.toByteArray(), "utf-8"));
                    builder.body(responseBody1);
                    builder.networkResponse(response.networkResponse());
                    builder.cacheResponse(response.cacheResponse());
                    builder.priorResponse(response.priorResponse());
                    response = builder.build();
                } catch (Exception e) {

                } finally {
                    if (byteArrayOutputStream != null) {
                        byteArrayOutputStream.close();
                    }
                    if (inputStream != null) {
                        inputStream.close();
                    }
                }
                //response.newBuilder().body(gzip(response.body()));
            }

        }
        return response;
    }
}
